//
//  StoreViewController.m
//  WGFGlobalHouse
//
//  Created by waiguofang on 15/4/15.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//  分销商 － 门店管理

#import "StoreViewController.h"
#import "ScroDeleteTableView.h"
#import "config.h"
#import "NodataCell.h"
#import "StoreManageCell.h"

#import "BrokerDM.h"
#import "MJRefresh.h"
#import "AcitonBayStyleTitleView.h"
#import "AddStoreVc.h"

#import "StoreDetaiViewController.h"
#import "FooterMenuView.h"
#import "MBProgressHUD+MJ.h"

@interface StoreViewController()<UITableViewDataSource,UITableViewDelegate,FooterMenuViewDelegate,StoreManageCellDelegate,ScroDeleteTableViewDelgate>

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic)ScroDeleteTableView *tableView;

@property(strong,nonatomic) NSArray *dataArray;
@property(strong,nonatomic) NodataCell *nodataCell;

@property(strong,nonatomic)BrokerDM *dm;
@property (nonatomic,strong) AcitonBayStyleTitleView *titleView;

@property (nonatomic,weak)FooterMenuView *footerView;

@property (nonatomic,assign)BOOL isEditModel;//是否点击导航拦上的‘编辑“
@property (nonatomic,assign)BOOL isClickAllBtn;// 是否点击了全选按钮


@end

@implementation StoreViewController
@synthesize dataArray,nodataCell,dm,titleView,footerView;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
     [self refreshData];
}

-(void)initView
{

    titleView = [AcitonBayStyleTitleView creadView];
    [[titleView abackBtn]addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    titleView.abackBtn.hidden = self.isHidden;
    titleView.abackBtn.enabled = !self.isHidden;
    [[titleView aaddBtn]addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
     [[titleView aeditBtn]addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];

    [[titleView atitleLab]setText:@"门店管理"];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:titleView];
    
    
   
    ScroDeleteTableView *tableView = [[ScroDeleteTableView alloc]initWithFrame: CGRectMake(0, self.headerView.frame.size.height, UIScreenWidth,UIScreenHeight - self.headerView.frame.size.height)];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.menuStatedelegate = self;
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    FooterMenuView *menuView = [FooterMenuView creatView];
    [self.view addSubview:menuView];
    footerView = menuView;
    footerView.moveBtn.hidden = YES;
    footerView.delegate = self;
    footerView.hidden = YES;
   
    
    //上拉刷新
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [self refreshData];
    }];
    
    dm = [[BrokerDM alloc]init];
    
    
}

#pragma mark 获取数据
-(void)refreshData
{
    [self.tableView reloadData];
    [nodataCell setState:nodataCellStateLoading];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       ResulteMod *mod =  [dm storemanagelistrefreshData];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (mod.resltState == ResultFail) {
                [nodataCell setCustTip:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [nodataCell setState:nodataCellStateNetError];
            }else{
                dataArray = [[NSArray alloc]initWithArray:mod.dataMod];
                if (dataArray.count ==0 || dataArray == nil) {
                    [nodataCell setState:nodataCellStateNodata];
                }
            }
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
       });
    });
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (dataArray == nil || dataArray.count == 0) {
        
        [tableView setScrollEnabled:false];
        return 1;
    }else
    {
         [tableView setScrollEnabled:YES];
        return dataArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dataArray == nil || dataArray.count == 0) {
        if (!nodataCell) {
            nodataCell = [[NodataCell alloc]initWithFrame:tableView.frame];
            [nodataCell setState:nodataCellStateLoading];
            nodataCell.refreshBtn.tag = 56;
            [nodataCell.refreshBtn  addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        return nodataCell;

    }
        static NSString *ID = @"storeMangeCell";
        StoreManageCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            
            cell = [[StoreManageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            [cell initWithTableView:tableView];
            cell.btndelegate = self;
            
        }
        
        cell.storeView.backBtn.tag = indexPath.row;
        [cell.storeView.backBtn  addTarget:self action:@selector(cellStoreBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.isEditModel = self.isEditModel;
        cell.model = [dataArray objectAtIndex:indexPath.row];
        
        return cell;
}



#pragma mark 点击cell，跳转到门店中的经纪人列表
-(void)cellStoreBtnOnClick:(UIButton *)btn
{
    if (self.isEditModel) {//编辑模式下，点击后显示打勾或不打勾
        StoreInfoModel  *data = [dataArray objectAtIndex:btn.tag];
    
        [data setIsSeleted:!data.isSeleted];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:btn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    }else//非编辑模式下，点击后跳转页面
    {
        StoreDetaiViewController *vc = [StoreDetaiViewController new];
        vc.storeModel = [dataArray objectAtIndexedSubscript:btn.tag];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dataArray.count == 0 || dataArray == nil) {
        return self.tableView.frame.size.height;
    }else
    {
        return [StoreManageCell getHeight];
    }
}
-(void)btnOnclick:(UIButton *)btn
{
    if (btn == nodataCell.refreshBtn) {
        
        [self refreshData];
    }else if (btn == titleView.abackBtn)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }else if (btn == titleView.aaddBtn)
    {
        AddStoreVc *vc = [AddStoreVc new];
        vc.lastvcType = isOtherVC;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (btn == titleView.aeditBtn)
    {
        if (dataArray == nil || dataArray.count == 0) {
            return;
        }
        footerView.hidden = self.isEditModel;
        self.isEditModel = !self.isEditModel;
        [self.tableView reloadData];
    }
}

#pragma mark footview的代理（全选，启用，禁用，移动）
#pragma mark 全选按钮被点击
-(void)footerMenuViewSelectAllBtnOnClicked;
{
    self.isClickAllBtn = !self.isClickAllBtn;
    [footerView.selectAllBtn setHighlighted:self.isEditModel];
    
    for (StoreInfoModel *model in dataArray) {
        model.isSeleted = self.isClickAllBtn;
    }
    [self.tableView reloadData];
}

#pragma mark 启用按钮
-(void)footerMenuViewBeAbleBtnOnClicked;
{
    if ([[self getAllStoreIds] isEqualToString:@"NO"]) {
        [MBProgressHUD showError:@"请至少选择一个客户"];
        return;
    }

    [self clickOnAbleOrUnAbleBtnUpdataWithStoreId:[self getAllStoreIds] WithStatus:@"0"];
}
#pragma mark 禁用按钮
-(void)footerMenuViewbeUnAbleBtnOnClicked;
{
    if ([[self getAllStoreIds] isEqualToString:@"NO"]) {
        [MBProgressHUD showError:@"请至少选择一个客户"];
        return;
    }
    [self clickOnAbleOrUnAbleBtnUpdataWithStoreId:[self getAllStoreIds] WithStatus:@"1"];
}

#pragma mark 点击了“禁用或启用后提交数据
-(void)clickOnAbleOrUnAbleBtnUpdataWithStoreId:(NSString *)storeId WithStatus:(NSString *)status;
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *mod = [dm batchmodifystorestatusWithStoreId:storeId WithStatus:status];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            [bself.footerView.selectAllBtn setImage:[UIImage imageNamed:@"fuxuan_birder"] forState:UIControlStateNormal];
            if (mod.resltState == ResultFail) {
                
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }
            else
            {
                [MBProgressHUD showSuccess:@"操作成功"];
                [bself refreshData];
            }
            
        });
    });
}
#pragma mark 获取被勾选所有门店的ID
-(NSString *)getAllStoreIds
{
    NSMutableArray *arrM = [NSMutableArray array];
    
    for (StoreInfoModel *model in dataArray) {
        if (model.isSeleted) {
            
            [arrM addObject:model.storeId];
        }
    }
    
    if (arrM.count == 0) {
        return @"NO";
    }
    return  [arrM componentsJoinedByString:@","];
}

#pragma mark storeMangeCell的代理，点击了“禁用，启用，编辑按钮
-(void)storeMangeCellFuntionBtnOnClick:(UIButton *)btn WithModel:(StoreInfoModel *)model
{
    switch (btn.tag) {
        case 101: //编辑
        {
            AddStoreVc *vc = [AddStoreVc new];
            vc.lastvcType = isStoreViewController;
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 102://禁用，启用
       
        {
            [MBProgressHUD showMessage:@"请稍等" toView:self.view];
            
            __weak typeof(self)bself = self;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                ResulteMod *mod = [dm modifystorestatusWithStoreId:model.storeId WithStatus:model.status == 0?@"1":@"0"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUDForView:bself.view animated:YES]
                    ;
                    if (mod.resltState == ResultFail) {
                        [MBProgressHUD showError:mod.resultTip];
                    }else if (mod.resltState == ResultNetError)
                    {
                        [MBProgressHUD showError:@"网络错误"];
                    }
                    else
                    {
                        [MBProgressHUD showSuccess:@"操作成功"];
                        [bself refreshData];
                    }
                });
            });
        }
            
            break;
            
        default:
            break;
    }
}

#pragma mark menuScroTableView delegate

-(void)cellMenDidHide:(UITableView*)tableView  cell:(ScroDeleteCell*)cell{
    
    StoreManageCell *brokerCell = (StoreManageCell *)cell;
    [brokerCell.storeView.rightBtn setImage:[UIImage imageNamed:@"right_back_shift"] forState:UIControlStateNormal];
}


-(void)cellMenDidShow:(UITableView*)tableView cell:(ScroDeleteCell*)cell{
    StoreManageCell *brokerCell = (StoreManageCell *)cell;
    [brokerCell.storeView.rightBtn setImage:[UIImage imageNamed:@"right_jiantou2"] forState:UIControlStateNormal];
    
}

@end
